class MaterialComparison {
    constructor() {
        this.scene = null;
        this.camera = null;
        this.renderer = null;
        this.controls = null;
        this.materials = {};
        this.meshes = {};
        this.lights = {};
        this.helpers = {};
        this.showHelpers = false;
        this.autoRotate = true;
        this.raycaster = new THREE.Raycaster();
        this.mouse = new THREE.Vector2();
        this.hoveredMesh = null;
        
        // 材质分类定义
        this.materialCategories = {
            basic: {
                name: '基础材质',
                materials: ['MeshBasicMaterial', 'MeshLambertMaterial', 'MeshPhongMaterial'],
                enabled: true
            },
            pbr: {
                name: 'PBR材质',
                materials: ['MeshStandardMaterial', 'MeshPhysicalMaterial'],
                enabled: true
            },
            special: {
                name: '特殊材质',
                materials: ['MeshToonMaterial', 'MeshNormalMaterial', 'MeshDepthMaterial'],
                enabled: true
            }
        };
        
        // 材质详细信息
        this.materialInfo = {
            MeshBasicMaterial: {
                name: '基础材质',
                englishName: 'MeshBasicMaterial',
                description: '不受光照影响的基础材质，适用于UI元素和发光物体',
                properties: ['color', 'opacity', 'transparent', 'wireframe'],
                propertyDetails: {
                    color: '基础颜色 (Color) - 材质的固有颜色，不受光照影响',
                    opacity: '透明度 (0-1) - 控制材质的不透明程度，1为完全不透明',
                    transparent: '透明开关 (Boolean) - 是否启用透明度计算',
                    wireframe: '线框模式 (Boolean) - 是否以线框方式渲染几何体'
                },
                lighting: '无光照响应',
                performance: '极高性能',
                useCase: 'UI界面、发光效果、简单几何体'
            },
            MeshLambertMaterial: {
                name: '朗伯材质',
                englishName: 'MeshLambertMaterial',
                description: '基于朗伯反射模型的漫反射材质，适用于粗糙表面',
                properties: ['color', 'opacity', 'transparent', 'wireframe'],
                propertyDetails: {
                    color: '漫反射颜色 (Color) - 材质在光照下的基础颜色',
                    opacity: '透明度 (0-1) - 控制材质的不透明程度',
                    transparent: '透明开关 (Boolean) - 是否启用透明度计算',
                    wireframe: '线框模式 (Boolean) - 是否以线框方式渲染'
                },
                lighting: '漫反射',
                performance: '高性能',
                useCase: '布料、纸张、粗糙表面'
            },
            MeshPhongMaterial: {
                name: '冯氏材质',
                englishName: 'MeshPhongMaterial',
                description: '支持镜面反射的材质，可产生高光效果',
                properties: ['color', 'specular', 'shininess', 'opacity', 'transparent', 'wireframe'],
                propertyDetails: {
                    color: '漫反射颜色 (Color) - 材质的基础颜色',
                    specular: '镜面反射颜色 (Color) - 高光的颜色，通常为白色或金属色',
                    shininess: '光泽度 (0-1000) - 控制高光的锐利程度，值越高高光越集中',
                    opacity: '透明度 (0-1) - 控制材质的不透明程度',
                    transparent: '透明开关 (Boolean) - 是否启用透明度计算',
                    wireframe: '线框模式 (Boolean) - 是否以线框方式渲染'
                },
                lighting: '漫反射 + 镜面反射',
                performance: '中等性能',
                useCase: '塑料、金属、光滑表面'
            },
            MeshStandardMaterial: {
                name: '标准PBR材质',
                englishName: 'MeshStandardMaterial',
                description: '基于物理的渲染材质，提供真实的光照效果',
                properties: ['color', 'metalness', 'roughness', 'opacity', 'transparent', 'wireframe'],
                propertyDetails: {
                    color: '基础颜色 (Color) - 材质的固有颜色',
                    metalness: '金属度 (0-1) - 0为非金属(电介质)，1为纯金属',
                    roughness: '粗糙度 (0-1) - 0为完全光滑(镜面)，1为完全粗糙(漫反射)',
                    opacity: '透明度 (0-1) - 控制材质的不透明程度',
                    transparent: '透明开关 (Boolean) - 是否启用透明度计算',
                    wireframe: '线框模式 (Boolean) - 是否以线框方式渲染'
                },
                lighting: '物理渲染(PBR)',
                performance: '中低性能',
                useCase: '真实感渲染、产品展示'
            },
            MeshPhysicalMaterial: {
                name: '物理材质',
                englishName: 'MeshPhysicalMaterial',
                description: '高级PBR材质，支持清漆层和透射等高级效果',
                properties: ['color', 'metalness', 'roughness', 'clearcoat', 'clearcoatRoughness', 'opacity', 'transparent', 'wireframe'],
                propertyDetails: {
                    color: '基础颜色 (Color) - 材质的固有颜色',
                    metalness: '金属度 (0-1) - 控制材质的金属特性',
                    roughness: '粗糙度 (0-1) - 控制表面的粗糙程度',
                    clearcoat: '清漆强度 (0-1) - 表面清漆层的强度，模拟汽车漆面效果',
                    clearcoatRoughness: '清漆粗糙度 (0-1) - 清漆层的粗糙程度',
                    opacity: '透明度 (0-1) - 控制材质的不透明程度',
                    transparent: '透明开关 (Boolean) - 是否启用透明度计算',
                    wireframe: '线框模式 (Boolean) - 是否以线框方式渲染'
                },
                lighting: '高级物理渲染',
                performance: '低性能',
                useCase: '高质量渲染、汽车漆面'
            },
            MeshToonMaterial: {
                name: '卡通材质',
                englishName: 'MeshToonMaterial',
                description: '非真实感渲染材质，产生卡通化的光照效果',
                properties: ['color', 'opacity', 'transparent', 'wireframe'],
                propertyDetails: {
                    color: '卡通颜色 (Color) - 材质的基础颜色，会产生分层光照效果',
                    opacity: '透明度 (0-1) - 控制材质的不透明程度',
                    transparent: '透明开关 (Boolean) - 是否启用透明度计算',
                    wireframe: '线框模式 (Boolean) - 是否以线框方式渲染'
                },
                lighting: '卡通化光照',
                performance: '中等性能',
                useCase: '卡通风格、游戏角色'
            },
            MeshNormalMaterial: {
                name: '法线材质',
                englishName: 'MeshNormalMaterial',
                description: '将法线向量映射为RGB颜色，用于调试和可视化',
                properties: ['opacity', 'transparent', 'wireframe'],
                propertyDetails: {
                    opacity: '透明度 (0-1) - 控制材质的不透明程度',
                    transparent: '透明开关 (Boolean) - 是否启用透明度计算',
                    wireframe: '线框模式 (Boolean) - 是否以线框方式渲染'
                },
                lighting: '无光照(显示法线)',
                performance: '高性能',
                useCase: '调试、法线可视化'
            },
            MeshDepthMaterial: {
                name: '深度材质',
                englishName: 'MeshDepthMaterial',
                description: '根据深度信息着色，用于深度可视化和特效',
                properties: ['opacity', 'transparent', 'wireframe'],
                propertyDetails: {
                    opacity: '透明度 (0-1) - 控制材质的不透明程度',
                    transparent: '透明开关 (Boolean) - 是否启用透明度计算',
                    wireframe: '线框模式 (Boolean) - 是否以线框方式渲染'
                },
                lighting: '无光照(显示深度)',
                performance: '高性能',
                useCase: '深度可视化、后处理效果'
            }
        };
        
        this.init();
    }
    
    init() {
        this.createScene();
        this.createCamera();
        this.createRenderer();
        this.createControls();
        this.createLights();
        this.createMaterials();
        this.createMeshes();
        this.createGround();
        this.setupEventListeners();
        this.animate();
        
        // 显示加载完成
        document.querySelector('.loading')?.remove();
    }
    
    createScene() {
        this.scene = new THREE.Scene();
        this.scene.background = new THREE.Color(0xf0f0f0);
        this.scene.fog = new THREE.Fog(0xf0f0f0, 50, 200);
    }
    
    createCamera() {
        const canvas = document.getElementById('three-canvas');
        const aspect = canvas.clientWidth / canvas.clientHeight;
        this.camera = new THREE.PerspectiveCamera(75, aspect, 0.1, 1000);
        this.camera.position.set(0, 15, 25);
        this.camera.lookAt(0, 0, 0);
    }
    
    createRenderer() {
        const canvas = document.getElementById('three-canvas');
        this.renderer = new THREE.WebGLRenderer({ 
            canvas: canvas, 
            antialias: true,
            alpha: true
        });
        this.renderer.setSize(canvas.clientWidth, canvas.clientHeight);
        this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
        this.renderer.shadowMap.enabled = true;
        this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
        this.renderer.outputEncoding = THREE.sRGBEncoding;
        this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
        this.renderer.toneMappingExposure = 1.2;
    }
    
    createControls() {
        this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);
        this.controls.enableDamping = true;
        this.controls.dampingFactor = 0.05;
        this.controls.maxPolarAngle = Math.PI / 2;
        this.controls.minDistance = 10;
        this.controls.maxDistance = 100;
    }
    
    createLights() {
        // 环境光（提供基础照明）
        this.lights.ambient = new THREE.AmbientLight(0x404040, 0.3);
        this.scene.add(this.lights.ambient);
        
        // 方向光（平行光）- 调整角度增强立体感
        this.lights.directional = new THREE.DirectionalLight(0xffffff, 2.5);
        this.lights.directional.position.set(15, 25, 15);
        this.lights.directional.castShadow = true;
        this.lights.directional.shadow.mapSize.width = 2048;
        this.lights.directional.shadow.mapSize.height = 2048;
        this.lights.directional.shadow.camera.near = 0.5;
        this.lights.directional.shadow.camera.far = 100;
        this.lights.directional.shadow.camera.left = -30;
        this.lights.directional.shadow.camera.right = 30;
        this.lights.directional.shadow.camera.top = 30;
        this.lights.directional.shadow.camera.bottom = -30;
        this.scene.add(this.lights.directional);
        
        // 创建环境贴图增强反射效果
        this.createEnvironmentMap();
        
        // 创建光源辅助器
        this.createLightHelpers();
    }
    
    createEnvironmentMap() {
        // 创建简单的环境贴图
        const pmremGenerator = new THREE.PMREMGenerator(this.renderer);
        const envTexture = pmremGenerator.fromScene(new THREE.Scene(), 0.04).texture;
        this.scene.environment = envTexture;
        
        // 创建天空盒效果
        const skyColor = 0x87CEEB; // 天空蓝
        const groundColor = 0x8B7355; // 地面棕
        const intensity = 0.6;
        const hemisphereLight = new THREE.HemisphereLight(skyColor, groundColor, intensity);
        this.scene.add(hemisphereLight);
        
        pmremGenerator.dispose();
    }
    
    createLightHelpers() {
        this.helpers.directional = new THREE.DirectionalLightHelper(this.lights.directional, 5);
        this.helpers.directionalShadow = new THREE.CameraHelper(this.lights.directional.shadow.camera);
        
        // 默认隐藏辅助器
        this.helpers.directional.visible = false;
        this.helpers.directionalShadow.visible = false;
        
        this.scene.add(this.helpers.directional);
        this.scene.add(this.helpers.directionalShadow);
    }
    
    createMaterials() {
        const baseColor = 0xffffff;
        
        // 基础材质
        this.materials.MeshBasicMaterial = new THREE.MeshBasicMaterial({ 
            color: baseColor,
            transparent: true
        });
        
        this.materials.MeshLambertMaterial = new THREE.MeshLambertMaterial({ 
            color: baseColor,
            transparent: true
        });
        
        this.materials.MeshPhongMaterial = new THREE.MeshPhongMaterial({ 
            color: baseColor,
            specular: 0x666666,  // 增强镜面反射
            shininess: 200,      // 提高光泽度
            transparent: true
        });
        
        // PBR材质 - 增强对比
        this.materials.MeshStandardMaterial = new THREE.MeshStandardMaterial({ 
            color: baseColor,
            metalness: 0.8,      // 增强金属感
            roughness: 0.2,      // 降低粗糙度
            transparent: true,
            envMapIntensity: 1.5 // 增强环境反射
        });
        
        this.materials.MeshPhysicalMaterial = new THREE.MeshPhysicalMaterial({ 
            color: baseColor,
            metalness: 0.9,      // 高金属度
            roughness: 0.1,      // 极低粗糙度
            clearcoat: 0.8,      // 增强清漆层
            clearcoatRoughness: 0.05, // 光滑清漆
            reflectivity: 1.0,   // 最大反射率
            transparent: true,
            envMapIntensity: 2.0 // 强环境反射
        });
        
        // 特殊材质
        this.materials.MeshToonMaterial = new THREE.MeshToonMaterial({ 
            color: baseColor,
            transparent: true
        });
        
        this.materials.MeshNormalMaterial = new THREE.MeshNormalMaterial({ 
            transparent: true
        });
        
        this.materials.MeshDepthMaterial = new THREE.MeshDepthMaterial({ 
            transparent: true
        });
    }
    
    createMeshes() {
        const geometry = new THREE.SphereGeometry(2.5, 64, 64); // 增大球体，增加细分
        const materialNames = Object.keys(this.materials);
        const spacing = 7; // 增加间距
        const cols = 4;
        
        materialNames.forEach((materialName, index) => {
            const material = this.materials[materialName];
            const mesh = new THREE.Mesh(geometry, material);
            
            // 计算位置
            const row = Math.floor(index / cols);
            const col = index % cols;
            const x = (col - (cols - 1) / 2) * spacing;
            const z = (row - 1) * spacing;
            
            mesh.position.set(x, 2, z);
            mesh.castShadow = true;
            mesh.receiveShadow = true;
            mesh.userData = { materialType: materialName };
            
            this.meshes[materialName] = mesh;
            this.scene.add(mesh);
            
            // 创建标签
            this.createLabel(materialName, x, z);
        });
    }
    
    createLabel(materialName, x, z) {
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');
        canvas.width = 256;
        canvas.height = 64;
        
        context.fillStyle = 'rgba(255, 255, 255, 0.9)';
        context.fillRect(0, 0, canvas.width, canvas.height);
        
        context.fillStyle = '#333';
        context.font = 'bold 16px Arial';
        context.textAlign = 'center';
        context.fillText(materialName, canvas.width / 2, canvas.height / 2 + 6);
        
        const texture = new THREE.CanvasTexture(canvas);
        const material = new THREE.SpriteMaterial({ map: texture });
        const sprite = new THREE.Sprite(material);
        
        sprite.position.set(x, -1, z);
        sprite.scale.set(4, 1, 1);
        
        this.scene.add(sprite);
    }
    
    createGround() {
        const geometry = new THREE.PlaneGeometry(50, 50);
        const material = new THREE.MeshLambertMaterial({ 
            color: 0xffffff,
            transparent: true,
            opacity: 0.8
        });
        
        const ground = new THREE.Mesh(geometry, material);
        ground.rotation.x = -Math.PI / 2;
        ground.position.y = -2;
        ground.receiveShadow = true;
        
        this.scene.add(ground);
    }
    
    setupEventListeners() {
        // 窗口大小调整
        window.addEventListener('resize', () => this.onWindowResize());
        
        // 鼠标移动事件
        this.renderer.domElement.addEventListener('mousemove', (event) => this.onMouseMove(event));
        
        // 材质分类控制
        Object.keys(this.materialCategories).forEach(categoryKey => {
            const checkbox = document.getElementById(`${categoryKey}-materials`);
            if (checkbox) {
                checkbox.addEventListener('change', (e) => {
                    this.materialCategories[categoryKey].enabled = e.target.checked;
                    this.updateMeshVisibility();
                });
            }
        });
        
        // 光源控制
        this.setupLightControls();
        
        // 材质属性控制
        this.setupMaterialControls();
        
        // 视图控制
        this.setupViewControls();
    }
    
    setupLightControls() {
        // 环境光强度
        const ambientSlider = document.getElementById('ambient-intensity');
        if (ambientSlider) {
            ambientSlider.addEventListener('input', (e) => {
                const value = parseFloat(e.target.value);
                this.lights.ambient.intensity = value;
                e.target.nextElementSibling.textContent = value.toFixed(2);
            });
        }
        
        // 方向光强度
        const directionalSlider = document.getElementById('directional-intensity');
        if (directionalSlider) {
            directionalSlider.addEventListener('input', (e) => {
                const value = parseFloat(e.target.value);
                this.lights.directional.intensity = value;
                e.target.nextElementSibling.textContent = value.toFixed(1);
            });
        }
        
        // 平行光 X 位置
        const directionalXSlider = document.getElementById('directional-x');
        if (directionalXSlider) {
            directionalXSlider.addEventListener('input', (e) => {
                const value = parseFloat(e.target.value);
                this.lights.directional.position.x = value;
                this.helpers.directional.update();
                e.target.nextElementSibling.textContent = value;
            });
        }
        
        // 平行光 Y 位置
        const directionalYSlider = document.getElementById('directional-y');
        if (directionalYSlider) {
            directionalYSlider.addEventListener('input', (e) => {
                const value = parseFloat(e.target.value);
                this.lights.directional.position.y = value;
                this.helpers.directional.update();
                e.target.nextElementSibling.textContent = value;
            });
        }
        
        // 平行光 Z 位置
        const directionalZSlider = document.getElementById('directional-z');
        if (directionalZSlider) {
            directionalZSlider.addEventListener('input', (e) => {
                const value = parseFloat(e.target.value);
                this.lights.directional.position.z = value;
                this.helpers.directional.update();
                e.target.nextElementSibling.textContent = value;
            });
        }
        
        // 光源辅助器显示控制
        const lightHelperCheckbox = document.getElementById('show-light-helper');
        if (lightHelperCheckbox) {
            lightHelperCheckbox.addEventListener('change', (e) => {
                const show = e.target.checked;
                this.helpers.directional.visible = show;
                this.helpers.directionalShadow.visible = show;
            });
        }
    }
    
    setupMaterialControls() {
        // 颜色控制
        const colorPicker = document.getElementById('material-color');
        if (colorPicker) {
            colorPicker.addEventListener('change', (e) => {
                const color = new THREE.Color(e.target.value);
                Object.values(this.materials).forEach(material => {
                    if (material.color) {
                        material.color.copy(color);
                    }
                });
            });
        }
        
        // 透明度控制
        const opacitySlider = document.getElementById('opacity');
        if (opacitySlider) {
            opacitySlider.addEventListener('input', (e) => {
                const value = parseFloat(e.target.value);
                Object.values(this.materials).forEach(material => {
                    material.opacity = value;
                    material.transparent = value < 1;
                });
                e.target.nextElementSibling.textContent = value.toFixed(2);
            });
        }
        
        // 线框模式
        const wireframeCheckbox = document.getElementById('wireframe');
        if (wireframeCheckbox) {
            wireframeCheckbox.addEventListener('change', (e) => {
                Object.values(this.materials).forEach(material => {
                    material.wireframe = e.target.checked;
                });
            });
        }
        
        // 自动旋转
        const autoRotateCheckbox = document.getElementById('auto-rotate');
        if (autoRotateCheckbox) {
            autoRotateCheckbox.addEventListener('change', (e) => {
                this.autoRotate = e.target.checked;
            });
        }
    }
    
    setupViewControls() {
        // 重置相机
        const resetButton = document.getElementById('reset-camera');
        if (resetButton) {
            resetButton.addEventListener('click', () => {
                this.camera.position.set(0, 15, 25);
                this.camera.lookAt(0, 0, 0);
                this.controls.reset();
            });
        }
        
        // 切换辅助线
        const helpersButton = document.getElementById('toggle-helpers');
        if (helpersButton) {
            helpersButton.addEventListener('click', () => {
                this.showHelpers = !this.showHelpers;
                Object.values(this.helpers).forEach(helper => {
                    helper.visible = this.showHelpers;
                });
                helpersButton.textContent = this.showHelpers ? '隐藏辅助线' : '显示辅助线';
            });
        }
        
        // 截图保存
        const screenshotButton = document.getElementById('screenshot');
        if (screenshotButton) {
            screenshotButton.addEventListener('click', () => {
                this.takeScreenshot();
            });
        }
    }
    
    updateMeshVisibility() {
        Object.keys(this.materialCategories).forEach(categoryKey => {
            const category = this.materialCategories[categoryKey];
            category.materials.forEach(materialName => {
                const mesh = this.meshes[materialName];
                if (mesh) {
                    mesh.visible = category.enabled;
                }
            });
        });
    }
    
    onMouseMove(event) {
        const canvas = this.renderer.domElement;
        const rect = canvas.getBoundingClientRect();
        
        this.mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
        this.mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
        
        this.raycaster.setFromCamera(this.mouse, this.camera);
        const intersects = this.raycaster.intersectObjects(Object.values(this.meshes));
        
        if (intersects.length > 0) {
            const mesh = intersects[0].object;
            if (this.hoveredMesh !== mesh) {
                this.hoveredMesh = mesh;
                this.showMaterialInfo(mesh.userData.materialType);
            }
        } else {
            if (this.hoveredMesh) {
                this.hoveredMesh = null;
                this.hideMaterialInfo();
            }
        }
    }
    
    showMaterialInfo(materialType) {
        const info = this.materialInfo[materialType];
        if (!info) return;
        
        const detailsDiv = document.getElementById('material-details');
        if (detailsDiv) {
            // 生成属性详细说明
            let propertyDetailsHtml = '';
            if (info.propertyDetails) {
                propertyDetailsHtml = '<div class="property-details"><h4>属性详解:</h4>';
                for (const [prop, detail] of Object.entries(info.propertyDetails)) {
                    propertyDetailsHtml += `<p><strong>${prop}:</strong> ${detail}</p>`;
                }
                propertyDetailsHtml += '</div>';
            }
            
            detailsDiv.innerHTML = `
                <div class="material-info-content">
                    <h3>${info.name} (${info.englishName})</h3>
                    <p><strong>描述:</strong> ${info.description}</p>
                    <p><strong>光照响应:</strong> ${info.lighting}</p>
                    <p><strong>性能表现:</strong> ${info.performance}</p>
                    <p><strong>适用场景:</strong> ${info.useCase}</p>
                    <p><strong>主要属性:</strong> ${info.properties.join(', ')}</p>
                    ${propertyDetailsHtml}
                </div>
            `;
        }
    }
    
    hideMaterialInfo() {
        const detailsDiv = document.getElementById('material-details');
        if (detailsDiv) {
            detailsDiv.innerHTML = '<p>将鼠标悬停在材质球体上查看详细信息</p>';
        }
    }
    
    takeScreenshot() {
        this.renderer.render(this.scene, this.camera);
        const canvas = this.renderer.domElement;
        const link = document.createElement('a');
        link.download = 'three-materials-comparison.png';
        link.href = canvas.toDataURL();
        link.click();
    }
    
    onWindowResize() {
        const canvas = document.getElementById('three-canvas');
        const width = canvas.clientWidth;
        const height = canvas.clientHeight;
        
        this.camera.aspect = width / height;
        this.camera.updateProjectionMatrix();
        this.renderer.setSize(width, height);
    }
    
    animate() {
        requestAnimationFrame(() => this.animate());
        
        // 自动旋转
        if (this.autoRotate) {
            Object.values(this.meshes).forEach(mesh => {
                mesh.rotation.x += 0.005;
                mesh.rotation.y += 0.01;
            });
        }
        
        // 更新控制器
        this.controls.update();
        
        // 更新辅助器
        if (this.helpers.spot) {
            this.helpers.spot.update();
        }
        
        // 渲染场景
        this.renderer.render(this.scene, this.camera);
    }
}

// 初始化应用
window.addEventListener('DOMContentLoaded', () => {
    new MaterialComparison();
});